<?php

namespace App\Http\Controllers\Api;

use App\Api\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Models\User;
use Doctrine\DBAL\Schema\AbstractAsset;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class TokenController extends BaseMiddleware
{
    use ApiResponse;

    //获取并更新token
    public function getToken(Request $request)
    {


//        oC9Xz5LqBZDVMtIfSrXJ58Jd3pQw
//        $openid = $request->openid;
//        $user = User::where('weixin_openid',$openid)->first();
//
//        $token= auth('api')->login($user);//登录,并获取jwt:token
////
//        dd($token);
//        // 检查此次请求中是否带有 token，如果没有则抛出异常。

//         使用 try 包裹，以捕捉 token 过期所抛出的 TokenExpiredException  异常
        try {
            // 检测用户的登录状态，如果正常则通过
            if ($this->auth->parseToken()->authenticate()) {

                $token = $request->token;
                $user = Auth::guard('api')->user();

                $data['user_id'] = $user->id;
                $data['user_name'] = $user->name;
                $data['user_avatar'] = $user->avatar;
                $data['token'] = $token;

                return $this->success($data);
            }
            throw new UnauthorizedHttpException('jwt-auth', '未登录');
        } catch (TokenExpiredException $exception) {
            // 此处捕获到了 token 过期所抛出的 TokenExpiredException 异常，我们在这里需要做的是刷新该用户的 token
            try {
                // 刷新用户的 token
                $token = $this->auth->refresh();

                // 使用一次性登录以保证此次请求的成功
                Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);

                return $this->setStatusCode(201)->message($token,'刷新token');

            } catch (JWTException $exception) {
                // 如果捕获到此异常，即代表 refresh 也过期了，用户无法刷新令牌，需要重新登录。

                return $this->failed('请重新登录','401');
//                throw new UnauthorizedHttpException('jwt-auth', $exception->getMessage());
            }
        }
    }
}
